import json
import uuid
import time
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support import expected_conditions as EC


class Base:
    def __init__(self, url='http://192.168.8.222/'):
        self.driver = webdriver.Edge()
        self.driver.maximize_window()
        self.driver.get(url)

    # 查找元素
    def find_element(self, loc, timeout=10):
        return WebDriverWait(self.driver, timeout=timeout).until(
            EC.visibility_of_element_located(loc)
        )

    # 进入iframe
    def go_iframe(self, loc):
        self.driver.switch_to.frame(self.find_element(loc))

    # 设置cookie
    def set_cookie(self, filename):
        self.driver.delete_all_cookies()
        with open(filename, "r", encoding="utf-8") as f:
            cookies = json.load(f)
            for c in cookies:
                self.driver.add_cookie(c)
            self.driver.refresh()

    # 设置cookie
    def save_cookie(self, filename):
        cookies = self.driver.get_cookies()
        with open(filename, "w", encoding="utf-8") as f:
            json.dump(cookies, f)

    # 点击元素
    def click(self, loc):
        self.find_element(loc).click()

    # 鼠标悬停
    def hover(self, loc):
        element = self.find_element(loc)
        ActionChains(self.driver).move_to_element(element).perform()

    # 获取文本
    def get_text(self, loc):
        return self.find_element(loc).text

    # 获取属性值
    def get_attribute(self, loc, value):
        return self.find_element(loc).get_attribute(value)

    # 输入数据
    def input(self, loc, value):
        el = self.find_element(loc)
        # 清空
        el.clear()
        # 输入
        el.send_keys(value)

    # 下拉框选项
    def select_value(self, loc, value):
        ele = self.find_element(loc)
        select = Select(ele)
        select.select_by_value(value)

    # 截图方法
    def get_image(self, name):
        filename = f'../png/{name}' + \
                   '{}'.format(time.strftime("%Y%m%d-%H%M%S")) + \
                   f'--login--error{str(uuid.uuid4())[0:4]}.png'
        self.driver.get_screenshot_as_file(filename)

    # 滚动到指定位置
    def scroll(self, loc):
        element = self.find_element(loc)
        self.driver.execute_script("arguments[0].scrollIntoView(true);", element)
